<?php

namespace app\modules\weixin\controllers;

use app\common\components\BaseWebController;
use app\common\components\HttpClient;
use app\common\services\UrlServices;
use app\common\services\UtilService;
use app\models\member\Member;
use Yii;
use yii\base\Exception;
use yii\helpers\Url;
use yii\web\Response;

class OauthController extends BaseWebController {
//  public function actionBind()
//  {
//    $scope = \Yii::$app->request->get('scope', 'snsapi_base');
//    $appid = \Yii::$app->params['weixin']['appid'];
//    $redirect_url = UrlServices::buildMUrl('/oauth/callback');
//    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}&response_type=code&scope={$scope}&state=STATE#wechat_redirect ";
//
//    return $this->redirect($url);
//  }

  public function actionParams()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    $appid = \Yii::$app->params['weixin']['appid'];
    $redirect_url = Yii::$app->request->getHostInfo() . Url::to('/weixin/oauth/callback');
    $data_info = ['appid' => $appid, 'redirect_url' => $redirect_url];
    return ['code' => 200, 'data' => $data_info];
  }

  public function actionCallback()
  {
    $code = \Yii::$app->request->get('code', '');
    if (!$code) {
      return false;
    }
    \Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      //通过code获取网页授权的access_token
      $appid = \Yii::$app->params['weixin']['appid'];
      $secret = \Yii::$app->params['weixin']['app_secret'];
      $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
      $result = HttpClient::get($url);
      $ret = @json_decode($result, true);
      $ret_token = isset($ret['access_token']) ? $ret['access_token'] : '';
      if (!$ret_token) {
        return false;
      }
      $openid = isset($ret['openid']) ? $ret['openid'] : '';
      $scope = isset($ret['scope']) ? $ret['scope'] : '';

      //获取用户具体信息
      $weixin_user_info = [];
      if ($scope == 'snsapi_userinfo') {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$ret_token}&openid={$openid}&lang=zh_CN";
        $wechat_user_info = HttpClient::get($url);
        $weixin_user_info = @json_decode($wechat_user_info, true);
      }
      //判断用户是否存在
      $member_info = Member::find()->where(['open_id' => $openid])->one();
      if (!$member_info) {
        $member_info = new Member();
        $member_info->open_id = $openid;
        $member_info->nickname = $weixin_user_info['nickname'];
        $member_info->sex = $weixin_user_info['sex'];
        $member_info->city = $weixin_user_info['city'];
        $member_info->province = $weixin_user_info['province'];
        $member_info->country = $weixin_user_info['country'];
        $member_info->avatar = $weixin_user_info['headimgurl'];
        $member_info->ip = UtilService::getIP();
//        $member_info->unionid = $weixin_user_info['unionid'];
        $member_info->lastlogin_time = time();
        $member_info->create_time = time();
        $member_info->save(0);
      } else {
        $member_info->lastlogin_time = time();
        $member_info->save(0);
      }
      \Yii::$app->session->set('user_info', $member_info);
      return ['code' => 200, 'data' => $member_info];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }


//        \Yii::$app->view->params['user_info'] = $member_info;
//        return $this->redirect(UrlServices::buildMUrl('/activity/index'));
  }
}
